package com.ruoyi.web.controller.shop.goods;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.resp.BuffetDetailDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/10
 **/
@Api("自助餐菜单明细")
@RestController
@RequestMapping("/shop/buffetDetail")
public class BuffetDetailController extends BaseController {
    @Resource
    private BuffetDetailService buffetDetailService;

    @Resource
    private BuffetService buffetService;

    @Resource
    private BuffetExamineService buffetExamineService;

    @Resource
    private BuffetExamineDetailService buffetExamineDetailService;

    @Resource
    private RestaurantGoodsService restaurantGoodsService;

    @ApiOperation("获取自助餐菜单明细")
    @GetMapping("/list")
    public TableDataInfo list(BuffetDetail buffetDetail)
    {
        startPage();
        List<BuffetDetail> buffetDetails = buffetDetailService.selectList(buffetDetail);
        return getDataTable(fillToDTO(buffetDetails));
    }

    @GetMapping("/listAll")
    public TableDataInfo listAll(BuffetDetail buffetDetail)
    {
        List<BuffetDetail> buffetDetails = buffetDetailService.selectList(buffetDetail);
        return getDataTable(fillToDTO(buffetDetails));
    }

    @GetMapping("/listTodayMorning")
    public TableDataInfo listTodayMorning()
    {
        Buffet query = new Buffet();
//        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.HOUR_OF_DAY, 0); // 将时设置为0
//        calendar.set(Calendar.MINUTE, 0);      // 将分设置为0
//        calendar.set(Calendar.SECOND, 0);      // 将秒设置为0
//        calendar.set(Calendar.MILLISECOND, 0);
//        query.setCreateTime(calendar.getTime());
        query.setStatus("启用");
        query.setType("早餐");
        List<Buffet> buffets = buffetService.selectList(query);
        if (CollectionUtils.isEmpty(buffets)) {
            return getDataTable(Collections.emptyList());
        }
        Buffet zao = buffets.get(0);
        List<BuffetDetail> buffetDetails = buffetDetailService.selectList(BuffetDetail.builder().buffetId(zao.getId()).build());
        return getDataTable(fillToDTO(buffetDetails));
    }

    @GetMapping("/listTodayEvening")
    public TableDataInfo listTodayEvening()
    {
        Buffet query = new Buffet();
//        Calendar calendar = Calendar.getInstance();
//        calendar.set(Calendar.HOUR_OF_DAY, 0); // 将时设置为0
//        calendar.set(Calendar.MINUTE, 0);      // 将分设置为0
//        calendar.set(Calendar.SECOND, 0);      // 将秒设置为0
//        calendar.set(Calendar.MILLISECOND, 0);
//        query.setCreateTime(calendar.getTime());
        query.setStatus("启用");
        query.setType("中餐");
        List<Buffet> buffets = buffetService.selectList(query);
        if (CollectionUtils.isEmpty(buffets)) {
            return getDataTable(Collections.emptyList());
        }
        Buffet zao = buffets.get(0);
        List<BuffetDetail> buffetDetails = buffetDetailService.selectList(BuffetDetail.builder().buffetId(zao.getId()).build());
        return getDataTable(fillToDTO(buffetDetails));
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(buffetDetailService.selectById(id));
    }

    @Log(title = "添加自助菜单明细", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody BuffetDetail buffetDetail)
    {
        buffetDetail.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = buffetDetailService.create(buffetDetail);
        if (!result) {
            return error();
        }
        syncBuffetExamineDetail(buffetDetail.getBuffetId(),"一区");
        syncBuffetExamineDetail(buffetDetail.getBuffetId(),"二区");
        return success();
    }

    @Log(title = "修改自助菜单明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody BuffetDetail buffetDetail) {
        buffetDetail.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = buffetDetailService.update(buffetDetail);
        if (!result) {
            return error();
        }
        BuffetDetail detail = buffetDetailService.selectById(buffetDetail.getId());
        syncBuffetExamineDetail(detail.getBuffetId(),"一区");
        syncBuffetExamineDetail(detail.getBuffetId(),"二区");
        return success();
    }

    @Log(title = "删除自助菜单明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        BuffetDetail buffetDetail = buffetDetailService.selectById(id);
        if (buffetDetail == null) {
            return success();
        }
        Boolean result = buffetDetailService.deleteById(id);
        if (!result) {
            return error();
        }
        syncBuffetExamineDetail(buffetDetail.getBuffetId(),"一区");
        syncBuffetExamineDetail(buffetDetail.getBuffetId(),"二区");

        return success();
    }

    private void syncBuffetExamineDetail(Long buffetId,String area) {
        BuffetExamine query=new BuffetExamine ();
        query.setArea(area);
        query.setBuffetId(buffetId);
        List<BuffetDetail> buffetDetails = buffetDetailService.selectList(BuffetDetail.builder().buffetId(buffetId).build());
        List<BuffetExamine> buffetExamines = buffetExamineService.selectList(query);
        // 属于异常情况
        if (CollectionUtils.isEmpty(buffetExamines)) {
            return;
        }
        BuffetExamine buffetExamine = buffetExamines.get(0);
        List<BuffetExamineDetail> buffetExamineDetails = buffetExamineDetailService.selectList(BuffetExamineDetail.builder().examineId(buffetExamine.getId()).build());
        Map<Long, BuffetDetail> buffetDetailMap;
        if (CollectionUtils.isEmpty(buffetDetails)) {
            buffetDetailMap = new HashMap<>();
        } else {
            buffetDetailMap = new HashMap<>();
            for (BuffetDetail buffetDetail : buffetDetails) {
                buffetDetailMap.put(buffetDetail.getGoodsId(), buffetDetail);
            }
        }
        Map<Long, BuffetExamineDetail> buffetExamineDetailMap;
        if (CollectionUtils.isEmpty(buffetExamineDetails)) {
            buffetExamineDetailMap = new HashMap<>();
        } else {
            buffetExamineDetailMap = new HashMap<>();
            for (BuffetExamineDetail buffetExamineDetail : buffetExamineDetails) {
                buffetExamineDetailMap.put(buffetExamineDetail.getGoodsId(), buffetExamineDetail);
            }
        }
        // 没有的则创建
        for (Long goodsId : buffetDetailMap.keySet()) {
            if (buffetExamineDetailMap.get(goodsId) == null) {
                BuffetExamineDetail buffetExamineDetail = new BuffetExamineDetail();
                buffetExamineDetail.setExamineId(buffetExamine.getId());
                buffetExamineDetail.setGoodsId(goodsId);
                buffetExamineDetail.setGoodsStatus("未检查");
                buffetExamineDetail.setPlatesStatus("未检查");
                buffetExamineDetail.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                buffetExamineDetailService.create(buffetExamineDetail);
            }
        }
        // 多余的删除
        for (Long goodsId : buffetExamineDetailMap.keySet()) {
            if (buffetDetailMap.get(goodsId) == null) {
                buffetExamineDetailService.deleteById(buffetExamineDetailMap.get(goodsId).getId());
            }
        }
    }

    private List<BuffetDetailDTO> fillToDTO(List<BuffetDetail> buffetDetails) {
        if (CollectionUtils.isEmpty(buffetDetails)) {
            return Collections.emptyList();
        }
        List<Long> goodsIds = buffetDetails.stream().map(BuffetDetail::getGoodsId).collect(Collectors.toList());
        List<RestaurantGoods> restaurantGoodsList = restaurantGoodsService.selectByIds(goodsIds);
        Map<Long, RestaurantGoods> restaurantGoodsMap;
        if (!CollectionUtils.isEmpty(restaurantGoodsList)) {
            restaurantGoodsMap = restaurantGoodsList.stream().collect(Collectors.toMap(RestaurantGoods::getId, g -> g));
        } else {
            restaurantGoodsMap = new HashMap<>();
        }
        return buffetDetails.stream().map(b -> {
            BuffetDetailDTO buffetDetailDTO = new BuffetDetailDTO();
            buffetDetailDTO.setId(b.getId());
            buffetDetailDTO.setBuffetId(b.getBuffetId());
            buffetDetailDTO.setGoodsId(b.getGoodsId());
            RestaurantGoods restaurantGoods = restaurantGoodsMap.get(b.getGoodsId());
            if (restaurantGoods != null) {
                buffetDetailDTO.setGoodsName(restaurantGoods.getName());
                buffetDetailDTO.setImage(restaurantGoods.getImage());
                buffetDetailDTO.setHun(restaurantGoods.getHun());
                buffetDetailDTO.setHot(restaurantGoods.getHot());
                buffetDetailDTO.setTaste(restaurantGoods.getTaste());
            }
            buffetDetailDTO.setCreateBy(b.getCreateBy());
            buffetDetailDTO.setCreateTime(b.getCreateTime());
            buffetDetailDTO.setUpdateBy(b.getUpdateBy());
            buffetDetailDTO.setUpdateTime(b.getUpdateTime());
            buffetDetailDTO.setRemark(b.getRemark());
            return buffetDetailDTO;
        }).collect(Collectors.toList());
    }
}
